package com.luoxiang.socialandroid.activity;

import static com.luoxiang.lib_common.common.Constants.MmkvConst.EXTRA;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.KEY;
import static com.luoxiang.lib_common.common.Constants.MmkvConst.TOKEN;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSStsTokenCredentialProvider;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.baidu.mapapi.search.sug.SuggestionResult;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.hw.videoprocessor.VideoProcessor;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luoxiang.socialandroid.R;
import com.luoxiang.socialandroid.adapter.SelectorphotoAdapter;
import com.luoxiang.socialandroid.base.BaseActivity;
import com.luoxiang.socialandroid.bean.NumberBean;
import com.luoxiang.socialandroid.bean.TokenBean;
import com.luoxiang.socialandroid.dialog.TipDialog;
import com.luoxiang.socialandroid.utils.AESUtil;
import com.luoxiang.socialandroid.utils.CustomClickListener;
import com.luoxiang.socialandroid.utils.GlideEngine;
import com.luoxiang.socialandroid.utils.MmkvUtil;
import com.luoxiang.socialandroid.utils.NetUtils2;
import com.lxj.xpopup.XPopup;
import com.tbruyelle.rxpermissions2.RxPermissions;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropImageEngine;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import cc.shinichi.library.ImagePreview;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.schedulers.Schedulers;
import kotlin.Unit;
import kotlin.jvm.functions.Function0;
import top.zibin.luban.Luban;
import top.zibin.luban.OnCompressListener;

public class OperationsActivity extends BaseActivity {
    public enum Operations {
        IMAGE,
        VIDEO,
        ALL,
    }

    private ImageView icon_back;
    private TextView tx_editsize, tx_tomyop, tx_posttion;
    private EditText ed_operations;
    private RecyclerView r_operation;
    private RelativeLayout r_toposition;
    private Button bt_publish;
    private String token, dynamic, location, latitudeAndLongitude, picturePath;
    //    private List<String> pathlist = new ArrayList<>();
    private static String paths, pathjson;
    private String[] path = new String[1];
    private ActivityResultLauncher<Intent> activityResultLauncher;
    private SuggestionResult.SuggestionInfo suggestionInfo;
    private SelectorphotoAdapter adapter;
    String aliyunnum;
    private ArrayList<String> listaliyun;
    private String videoFile;
    private String mimeType, pathsvideo;
    private ImageView add_video;
    private Button icon_clearthis;
    private ArrayList<LocalMedia> list;
    private Operations operations = Operations.ALL;
    private View viewIconChuanImage;
    private TextView wodeweizhi666;

    @Override
    protected void initListener() {
        icon_back.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                TipDialog tipDialog = new TipDialog(OperationsActivity.this);
                tipDialog.setTitle(getString(R.string.mi_caozuotishi));
                tipDialog.setCancel(getString(R.string.mi_quxiao));
                tipDialog.setContent(getString(R.string.mi_dialog_bianjituichu_content));
                tipDialog.setConfirm(getString(R.string.mi_queding));
                tipDialog.setOnCancelClickListener(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        tipDialog.dismiss();
                        return null;
                    }
                });
                tipDialog.setOnConfirmClickListener(new Function0<Unit>() {
                    @Override
                    public Unit invoke() {
                        finish();
                        tipDialog.dismiss();
                        return null;
                    }
                });
                new XPopup.Builder(OperationsActivity.this)
                        .asCustom(tipDialog)
                        .show();
            }

            @Override
            protected void onFastClick() {

            }
        });
        r_toposition.setOnClickListener(view -> {
            //点击应获取定位权限
            initScreenRecorderBuild();

        });
        tx_tomyop.setOnClickListener(view -> {
            Intent intent = new Intent(OperationsActivity.this, MyOperationsActivity.class);
            intent.putExtra("intentflag", 6);
            startActivity(intent);
        });
        ed_operations.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                tx_editsize.setText(String.valueOf(ed_operations.getText().length()));
            }
        });
        viewIconChuanImage.setOnClickListener(new CustomClickListener() {
            @Override
            protected void onSingleClick() {
                //动态申请权限
                if (ContextCompat.checkSelfPermission(OperationsActivity.this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(OperationsActivity.this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, 1);
                } else {
                    //访问相册
                    InputPicture();
                }
            }

            @Override
            protected void onFastClick() {

            }
        });
        adapter.setOnDeleteClickListener(new Function0<Unit>() {
            @Override
            public Unit invoke() {
                if (list.size() == 9) {
                    adapter.removeFooterView(viewIconChuanImage);
                } else {
                    if (!adapter.hasFooterLayout()) {
                        adapter.addFooterView(viewIconChuanImage);
                    }
                }
                return null;
            }
        });
    }

    private void initScreenRecorderBuild() {
        RxPermissions rxPermissions = new RxPermissions(OperationsActivity.this);
        rxPermissions.request(
                Manifest.permission.ACCESS_FINE_LOCATION

        ).subscribe(new Consumer<Boolean>() {
            @Override
            public void accept(Boolean aBoolean) throws Exception {
                if (aBoolean) {
                    Intent intent = new Intent(OperationsActivity.this, PositionActivity.class);
                    activityResultLauncher.launch(intent);
                } else {
                    Intent intent = new Intent(OperationsActivity.this, PositionActivity.class);
                    activityResultLauncher.launch(intent);
                    ToastUtils.showShort(R.string.mi_weihuoqudaodingweiquanxian);
                }
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if ((keyCode == KeyEvent.KEYCODE_BACK)) {
            TipDialog tipDialog = new TipDialog(OperationsActivity.this);
            tipDialog.setTitle(getString(R.string.mi_caozuotishi));
            tipDialog.setCancel(getString(R.string.mi_quxiao));
            tipDialog.setContent(getString(R.string.mi_dialog_bianjituichu_content));
            tipDialog.setConfirm(getString(R.string.mi_queding));
            tipDialog.setOnCancelClickListener(new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    tipDialog.dismiss();
                    return null;
                }
            });
            tipDialog.setOnConfirmClickListener(new Function0<Unit>() {
                @Override
                public Unit invoke() {
                    finish();
                    tipDialog.dismiss();
                    return null;
                }
            });
            new XPopup.Builder(OperationsActivity.this)
                    .asCustom(tipDialog)
                    .show();
            return false;

        } else {

            return super.onKeyDown(keyCode, event);

        }
    }

    private void publish(String extra, String token, String dynamic, int i, String toString, String s, String s1) {
        getRequest();
        Gson gson = new Gson();
        String jsonpathss = gson.toJson(path);
        LogUtils.i("jsonpathss", jsonpathss);
        LogUtils.i("qqwwees", paths);
        LogUtils.i("qqwwee", path);
        NetUtils2.getInstance().getApiService().publishDynamic(extra, token, i, dynamic, 0, toString, s, s1)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrop", decryptStr);
                            Gson gson = new Gson();
                            TokenBean tokenBean = gson.fromJson(decryptStr, TokenBean.class);

                            if (tokenBean.getCode() == 0) {
                                ToastUtils.showShort(R.string.mi_fabudongtaichenggong);
                                clearLoading();
                                finish();
                            } else {
                                ToastUtils.showShort(tokenBean.getMsg());
                                clearLoading();
                            }

                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        clearLoading();
                    }

                    @Override
                    public void onComplete() {
                        clearLoading();
                    }
                });
    }

    @Override
    protected void initLayout(Bundle savedInstanceState) {
        setContentView(R.layout.activity_operations);
        setStatusBarTranslucent();
    }

    @Override
    protected void initView() {
        getRequest();
        list = new ArrayList<>();
        token = MmkvUtil.INSTANCE.decodeString(TOKEN);
        icon_back = findViewById(R.id.icon_back);
        ed_operations = findViewById(R.id.ed_operations);
        tx_editsize = findViewById(R.id.tx_editsize);
        tx_tomyop = findViewById(R.id.tx_tomyop);
        r_operation = findViewById(R.id.rc_operations);
        r_toposition = findViewById(R.id.r_toposition);
        bt_publish = findViewById(R.id.bt_publish);
        tx_posttion = findViewById(R.id.tx_position);
        add_video = findViewById(R.id.add_video);
        wodeweizhi666 = findViewById(R.id.wodeweizhi666);
        icon_clearthis = findViewById(R.id.icon_clearthis);
        viewIconChuanImage = LayoutInflater.from(this).inflate(R.layout.view_icon_chuan_image, null);
        tx_editsize.setText("0");
        activityResultLauncher = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode() == Activity.RESULT_OK) {
                if (result.getData() != null) {
                    suggestionInfo = result.getData().getParcelableExtra("suggestionInfo");
                    if (suggestionInfo != null) {
                        wodeweizhi666.setText(suggestionInfo.key);
                        wodeweizhi666.setTextColor(Color.parseColor("#333333"));
                        wodeweizhi666.setTextSize(16);
                        tx_posttion.setVisibility(View.GONE);
                    } else {
                        wodeweizhi666.setText("");
                    }
                } else {
                    wodeweizhi666.setText("");
                }
            }
        });
        adapter = new SelectorphotoAdapter(list);
        adapter.addFooterView(viewIconChuanImage, -1, LinearLayout.HORIZONTAL);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(OperationsActivity.this, LinearLayoutManager.HORIZONTAL, false);
        r_operation.setLayoutManager(linearLayoutManager);
        r_operation.setAdapter(adapter);
//        String endpoint = "http://oss-cn-hangzhou.aliyuncs.com";
//// 填写STS应用服务器地址。
//        String stsServer = "https://example.com";
//// 推荐使用OSSAuthCredentialsProvider。token过期可以及时更新。
//        OSSCredentialProvider credentialProvider = new OSSAuthCredentialsProvider(stsServer);
//
//// 配置类如果不设置，会有默认配置。
//        ClientConfiguration conf = new ClientConfiguration();
//        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
//        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
//        conf.setMaxConcurrentRequest(5); // 最大并发请求数，默认5个。
//        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
//
//        OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider);
//
//        OSSAsyncTask task = oss.asyncGetObject();
//        task.cancel(); // 取消任务
//        task.waitUntilFinished(); // 等待直到任务完成
//        GetObjectResult result = task.getResult(); // 阻塞等待结果返回
    }

    public void setOperations(Operations operations) {
        this.operations = operations;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == 1) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                InputPicture();
            } else {
                Toast.makeText(this, R.string.mi_jujuequanxianwufajinxingcaozuo, Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    private void InputPicture() {
        int openGallery = SelectMimeType.ofAll();
        switch (operations) {
            case IMAGE: {
                openGallery = SelectMimeType.ofImage();
                break;
            }
            case VIDEO: {
                openGallery = SelectMimeType.ofVideo();
                break;
            }
        }
        PictureSelector.create(this)
                .openGallery(openGallery)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setMaxSelectNum(9 - list.size())
                .setCropEngine((fragment, srcUri, destinationUri, dataSource, requestCode) -> {
                    // 注意* 如果你实现自己的裁剪库，需要在Activity的.setResult();
                    // Intent中需要给MediaStore.EXTRA_OUTPUT，塞入裁剪后的路径；如果有额外数据也可以通过CustomIntentKey.EXTRA_CUSTOM_EXTRA_DATA字段存入；
                    UCrop uCrop = UCrop.of(srcUri, destinationUri, dataSource);
                    uCrop.setImageEngine(new UCropImageEngine() {
                        @Override
                        public void loadImage(Context context, String url, ImageView imageView) {
                            Glide.with(context).load(url).into(imageView);
                        }

                        @Override
                        public void loadImage(Context context, Uri url, int maxWidth, int maxHeight, OnCallbackListener<Bitmap> call) {
                            Glide.with(context).asBitmap().override(maxWidth, maxHeight).load(url).into(new CustomTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
                                    if (call != null) {
                                        call.onCall(resource);
                                    }
                                }

                                @Override
                                public void onLoadFailed(@Nullable Drawable errorDrawable) {
                                    if (call != null) {
                                        call.onCall(null);
                                    }
                                }

                                @Override
                                public void onLoadCleared(@Nullable Drawable placeholder) {
                                }
                            });
                        }
                    });
                    uCrop.start(fragment.requireActivity(), fragment, requestCode);
                })
                .forResult(new OnResultCallbackListener<LocalMedia>() {
                    @Override
                    public void onResult(ArrayList<LocalMedia> result) {
                        if (result.isEmpty()) {
                            return;
                        } else {

                            if (list.size() + result.size() == 9) {
                                adapter.removeFooterView(viewIconChuanImage);
                            } else {
                                if (!adapter.hasFooterLayout()) {
                                    adapter.addFooterView(viewIconChuanImage);
                                }
                            }
                            String s = result.toString();
                            LogUtils.i("resultstring", s);
                            videoFile = result.get(0).getRealPath();
                            String realPath = result.get(0).getRealPath();
                            LogUtils.i("videoFile", videoFile);
                            LogUtils.i("realPath", realPath);
                            mimeType = result.get(0).getMimeType();
                            LogUtils.i("mimetype", mimeType);
                            if (mimeType.equals("video/mp4")) {
                                if (result.get(0).getPath() != null) {
                                    operations = Operations.VIDEO;
                                    Glide.with(OperationsActivity.this)
                                            .asBitmap()
                                            .load(result.get(0).getPath())
                                            .override(300, 300)
                                            .transform(new CenterCrop(), new RoundedCorners(8))
                                            .placeholder(com.luck.picture.lib.R.drawable.ps_image_placeholder)
                                            .into(add_video);

                                    add_video.setVisibility(View.VISIBLE);
                                    adapter.removeFooterView(viewIconChuanImage);
                                    icon_clearthis.setVisibility(View.VISIBLE);
                                    icon_clearthis.setOnClickListener(new CustomClickListener() {
                                        @Override
                                        protected void onSingleClick() {
                                            adapter.addFooterView(viewIconChuanImage);
                                            icon_clearthis.setVisibility(View.GONE);
                                            add_video.setVisibility(View.GONE);
                                            videoFile = null;
                                            operations = Operations.ALL;

                                        }

                                        @Override
                                        protected void onFastClick() {

                                        }
                                    });
                                } else {
                                    Glide.with(OperationsActivity.this)
                                            .asBitmap()
                                            .load(result.get(0).getRealPath())
                                            .override(300, 300)
                                            .transform(new CenterCrop(), new RoundedCorners(8))
                                            .placeholder(com.luck.picture.lib.R.drawable.ps_image_placeholder)
                                            .into(add_video);
                                    add_video.setVisibility(View.VISIBLE);
                                    adapter.removeFooterView(viewIconChuanImage);

                                }
                                add_video.setOnClickListener(new CustomClickListener() {
                                    @Override
                                    protected void onSingleClick() {
                                        //点击跳转预览视频
                                        Intent intent = new Intent(OperationsActivity.this, SeevideoActivity.class);
                                        intent.putExtra("pathvideo", result.get(0).getRealPath());
                                        startActivity(intent);
                                    }

                                    @Override
                                    protected void onFastClick() {

                                    }
                                });
                            } else {
                                list.addAll(result);
                                operations = Operations.IMAGE;
                                adapter.notifyDataSetChanged();
                                adapter.setOnItemAddClickListener((position, path) -> {
                                    ImagePreview
                                            .getInstance()
                                            .setContext(OperationsActivity.this)
                                            .setImage(path)
                                            .start();
                                    return null;
                                });
                            }


//                            Glide.with(OperationsActivity.this)
//                                    .load(Uri.fromFile(file))
//                                    .into(add_img);


                        }
                        bt_publish.setOnClickListener(new CustomClickListener() {
                            @Override
                            protected void onSingleClick() {
                                showLoading();
//                                if (videoFile!=null&&list!=null){
//                                    ToastUtils.showShort("不可以同时选择照片和视频");
//                                }else {
//
//                                }
                                String s = "";
                                String s1 = "";
                                if (suggestionInfo != null) {
                                    s = suggestionInfo.key;
                                    s1 = suggestionInfo.getPt().longitude + "," + suggestionInfo.pt.latitude;
                                }
                                listaliyun = new ArrayList();
                                if (mimeType.equals("video/mp4")) {
                                    Observable.fromCallable(() -> {
                                                long time = System.currentTimeMillis();
                                                VideoProcessor.processor(OperationsActivity.this)
                                                        .input(videoFile)
                                                        .output(OperationsActivity.this.getCacheDir().getAbsolutePath() + "/" + time + ".mp4")
                                                        .process();
                                                videoFile = new File(OperationsActivity.this.getCacheDir().getAbsolutePath() + "/" + time + ".mp4").getAbsolutePath();
                                                return videoFile;
                                            }).subscribeOn(Schedulers.io())
                                            .observeOn(AndroidSchedulers.mainThread())
                                            .subscribe(path -> {
                                                //代表当前选中为视频
                                                String getkeyvideo = getkey(path);
                                                pathsvideo = getkeyvideo;
                                                getTokenvideo(path);
                                                LogUtils.i("pathsvideo", pathsvideo);
                                                ArrayList<String> list = new ArrayList();
                                                list.add(pathsvideo);
                                                Gson gson = new Gson();
                                                String arraytojson = gson.toJson(list);
                                                String s5 = "";
                                                String s6 = "";
                                                if (suggestionInfo != null) {
                                                    s5 = suggestionInfo.key;
                                                    s6 = suggestionInfo.getPt().longitude + "," + suggestionInfo.pt.latitude;
                                                }
                                                publish(EXTRA, token, arraytojson, 1, ed_operations.getText().toString(), s5, s6);
                                            });
                                } else {
                                    getToken(list, 0);
                                }
                            }

                            @Override
                            protected void onFastClick() {
                                ToastUtils.showShort("检测到您点击过快，请稍等重试");
                            }
                        });
//                        } else {
//                            ToastUtils.showShort("请上传图片后重试");
//                        }
                    }

                    @Override
                    public void onCancel() {

                    }
                });
    }

    public void getTokenvideo(String picturePaths) {
        getRequest();
//        List<String> paths=new ArrayList<>();
        getRequest();
        NetUtils2.getInstance().getApiService().getUploadToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {


                            LogUtils.i("decryptStrpp", decryptStr);
                            Gson gson = new Gson();
                            TokenBean tokenBean = gson.fromJson(decryptStr, TokenBean.class);
                            if (tokenBean != null) {
                                String endpoint = tokenBean.getData().getSts().getEndpoint();

                                // 在移动端建议使用STS的方式初始化OSSClient。
                                OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(tokenBean.getData().getSts().getAccessKeyId(), tokenBean.getData().getSts().getAccessKeySecret(), tokenBean.getData().getSts().getSecurityToken());

                                ClientConfiguration conf = new ClientConfiguration();
                                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
                                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。


                                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
                                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。

                                OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
//                                for (String localPath:picturePaths) {

                                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/HHmmss/");
                                Date date = new Date(System.currentTimeMillis());
                                String uuid = UUID.randomUUID().toString().replaceAll("-", "");
                                //文件后缀   例如：.png
                                String fileType = picturePaths.substring(picturePaths.lastIndexOf("."));
//                                String path = "exampledir/exampleobject.txt";

                                LogUtils.i("pathiii", key);
                                // 构造上传请求。
//                                2022/09/29/191405/UUID.PNG
                                PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), pathsvideo, picturePaths);

                                putObjectRequest.setProgressCallback(new OSSProgressCallback<PutObjectRequest>() {
                                    @Override
                                    public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                                    }
                                });
                                OSSAsyncTask ossAsyncTask = oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                    @Override
                                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
//                                        paths.add(path);
                                        LogUtils.d("aliossresult", "上传成功" + "diyi\t\t" + result.toString() + "\t\tdier=" + request.toString());
                                    }

                                    @Override
                                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                        LogUtils.d("aliossresult", "上传失败" + serviceException.getErrorCode() + serviceException.getMessage());

                                    }
                                });
                            }

                        } catch (Exception e) {
                            LogUtils.e("osslog", e.getMessage());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        if (requestCode == 1 && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            picturePath = cursor.getString(columnIndex);


        }
        super.onActivityResult(requestCode, resultCode, data);

    }

    public void getToken(List<LocalMedia> localMediaList, int index) {
        if (index >= localMediaList.size()) {
            //拿到图片上传后台
            String s = "";
            String s1 = "";
            if (suggestionInfo != null) {
                s = suggestionInfo.key;
                s1 = suggestionInfo.getPt().longitude + "," + suggestionInfo.pt.latitude;

            }
            Gson gson = new Gson();
            aliyunnum = gson.toJson(listaliyun);

            publish(EXTRA, token, aliyunnum, 0, ed_operations.getText().toString(), s, s1);
            return;
        }
        String path = localMediaList.get(index).getCutPath();
        picturePath = getkey(path);

        getRequest();
        NetUtils2.getInstance().getApiService().getUploadToken()
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<NumberBean>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(NumberBean numberBean) {
                        String data = numberBean.getData();
                        String decryptStr = null;
                        try {
                            decryptStr = AESUtil.aesDecryptString(data, KEY);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            LogUtils.i("decryptStrpp", decryptStr);
                            Gson gson = new Gson();
                            TokenBean tokenBean = gson.fromJson(decryptStr, TokenBean.class);
                            if (tokenBean != null) {
                                String endpoint = tokenBean.getData().getSts().getEndpoint();

                                // 在移动端建议使用STS的方式初始化OSSClient。
                                OSSCredentialProvider credentialProvider = new OSSStsTokenCredentialProvider(tokenBean.getData().getSts().getAccessKeyId(), tokenBean.getData().getSts().getAccessKeySecret(), tokenBean.getData().getSts().getSecurityToken());
                                ClientConfiguration conf = new ClientConfiguration();
                                conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒。
                                conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒。
                                conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个。
                                conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次。
                                OSS oss = new OSSClient(getApplicationContext(), endpoint, credentialProvider, conf);
                                Luban.with(OperationsActivity.this)
                                        .load(path)
                                        .ignoreBy(500)
                                        .setCompressListener(new OnCompressListener() {
                                            @Override
                                            public void onStart() {
                                            }

                                            @Override
                                            public void onSuccess(File file) {
                                                PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), picturePath, file.getPath());
                                                oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                                    @Override
                                                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                                        listaliyun.add(picturePath);
                                                        getToken(localMediaList, index + 1);
                                                        LogUtils.d("aliossresult", "上传成功" + result.toString());

                                                    }

                                                    @Override
                                                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                                        LogUtils.d("aliossresult", "上传失败");
                                                    }
                                                });
                                            }

                                            @Override
                                            public void onError(Throwable e) {
                                                PutObjectRequest putObjectRequest = new PutObjectRequest(tokenBean.getData().getSts().getBucketName(), picturePath, path);
                                                oss.asyncPutObject(putObjectRequest, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
                                                    @Override
                                                    public void onSuccess(PutObjectRequest request, PutObjectResult result) {
                                                        listaliyun.add(picturePath);
                                                        getToken(localMediaList, index + 1);
                                                        LogUtils.d("aliossresult", "上传成功" + result.toString());

                                                    }

                                                    @Override
                                                    public void onFailure(PutObjectRequest request, ClientException clientException, ServiceException serviceException) {
                                                        LogUtils.d("aliossresult", "上传失败");
                                                    }
                                                });
                                            }
                                        }).launch();
                            }
                        } catch (Exception e) {
                        }
                    }

                    @Override
                    public void onError(Throwable e) {

                    }

                    @Override
                    public void onComplete() {

                    }
                });

    }


}
